/**
 *
 */
package com.nightwalker.xsite.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.nightwalker.xsite.bean.TipoBean;
import com.nightwalker.xsite.infra.ErroGraveException;

/**
 * TipoDao
 * <br><br>
 * <b>Description:</b>
 * <br><br>
 * Created in Jan 30, 2008 2:12:56 PM
 * <br>
 * <b>version:</b>
 * <br>
 * <b>Modifications:</b>
 */
public class TipoDao extends Dao {

	public TipoBean recuperarTipos(TipoBean tipo) {

		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		StringBuilder query = new StringBuilder("SELECT id, tipo FROM tipos");

		try {
			log.debug("Consultando tipos(preparedStatment): " + query.toString());

			preparedStatement = conexao.prepareStatement(query.toString());
			resultSet = preparedStatement.executeQuery();

			List<TipoBean> tipos = tipo.getTipos();

			TipoBean tipoOut;

			while (resultSet.next()) {
				tipoOut = new TipoBean();
				tipoOut.setId(resultSet.getString("id"));
				tipoOut.setTipo(resultSet.getString("tipo"));

				tipos.add(tipoOut);
			}

			log.info("Foram encontrados " + tipos.size() + " tipos");

			return tipo;

		} catch (SQLException e) {
			log.error("Erro ao recuperar os tipos: ", e);
			throw new ErroGraveException(e);
		} finally {
			try {
				if (resultSet != null) {
					resultSet.close();
				}

				if (preparedStatement != null) {
					preparedStatement.close();
				}

			} catch (SQLException e) {
				log.error("Erro ao fechar resultSet ou statment: ", e);
			}
		}
	}

	public int incluirTipo(TipoBean tipo){
		PreparedStatement preparedStatement = null;

		StringBuilder query = new StringBuilder("insert into tipos (tipo) value (?)");

		try {
			log.debug("Incluindo tipo(preparedStatment): "+ query.toString());
			preparedStatement = conexao.prepareStatement(query.toString());

			preparedStatement.setString(1, tipo.getTipo());

			return preparedStatement.executeUpdate();

		} catch (SQLException e) {
			log.error("Erro ao inserir tipo: ", e);
			throw new ErroGraveException(e);
		} finally {
			try {
				if (preparedStatement != null){
					preparedStatement.close();
				}

			} catch (SQLException e) {
				log.error("Erro ao fechar statment: ", e);
			}
		}
	}
}
